package com.shell.customer.register.rx;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.Encryptor;
import com.shell.bee.base.utils.JsonUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.customer.register.RegisterEvent;
import com.shell.customer.register.vo.RegisterVo;
import com.shell.dto.UserAndOrganDto;
import com.shell.feign.PubUserFeign;
import com.shell.feign.UserOrganFeign;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.governor.organization.vo.PubOrganVo;
import com.shell.governor.user.po.PubUser;
import com.shell.governor.user.vo.PubUserVo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SaveUserAndOrganSubscriber
  extends OnErrorNotImplementedSubscriber<RegisterEvent>
{
  @Autowired
  private PubUserFeign pubUserFeign;
  @Autowired
  private UserOrganFeign userOrganFeign;
  
  public void onApplicationEvent(RegisterEvent event)
  {
    RegisterVo registerVo = event.getRegisterVo();
    
    PubOrganVo organVo = new PubOrganVo();
    organVo.setOrganId(registerVo.getCusId());
    organVo.setOrganName(registerVo.getCusName());
    organVo.setShortName(registerVo.getCusName());
    organVo.setOrganState("I");
    organVo.setOrganType("ENT");
    organVo.setSourceCode("EXTERNAL");
    organVo.setParentCode("OG001");
    
    PubUserVo pubUser = new PubUserVo();
    pubUser.setUserState("E");
    if (StringUtil.notEmpty(registerVo.getPassword()))
    {
      pubUser.setUserId(registerVo.getContactorId());
      pubUser.setPassword(Encryptor.encryptWithMD5(registerVo.getPassword()));
      pubUser.setPhoneNo(registerVo.getContactorPhone());
      pubUser.setUserName(registerVo.getContactorName());
      pubUser.setCreatorId(registerVo.getContactorId());
      pubUser.setCreateTime(DateUtil.getSystemDateTime());
      pubUser.setEntId(registerVo.getCusId());
      pubUser.setOrganId(registerVo.getCusId());
    }
    else
    {
      PubUser user = this.pubUserFeign.selectByKey(registerVo.getContactorId());
      BeanUtils.copyProperties(user, pubUser);
    }
    pubUser.setEntId(organVo.getOrganId());
    pubUser.setOrganId(organVo.getOrganId());
    
    List<PubUserVo> userVos = new ArrayList();
    userVos.add(pubUser);
    
    UserAndOrganDto dto = new UserAndOrganDto();
    dto.setUsers(userVos);
    dto.setOrgan(organVo);
    try
    {
      this.userOrganFeign.saveOrUpdateUserAndOrgan(JsonUtil.toJson(dto));
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw new UnCheckMsgException("������������������������");
    }
  }
}
